import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/Layout.vue'
import Login from '@/views/Login.vue'
import Weekly from '@/views/weekly/Weekly.vue'
import WeeklyStats from '@/views/weekly/WeeklyStats.vue'
import TeamStats from '@/views/team/TeamStats.vue'
import Projects from '@/views/projects/Projects.vue'
import Work from '@/views/work/Work.vue'
import Habits from '@/views/habits/Habits.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { noRequireAuth: true }
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/Home.vue')
      },
      {
        path: 'habits',
        name: 'Habits',
        component: Habits
      },
      {
        path: 'schedule',
        name: 'Schedule',
        component: () => import('@/views/schedule/Schedule.vue')
      },
      {
        path: 'todo',
        name: 'Todo',
        component: () => import('@/views/todo/Todo.vue')
      },
      {
        path: 'weekly',
        name: 'Weekly',
        component: Weekly
      },
      {
        path: 'weekly-stats',
        name: 'WeeklyStats',
        component: WeeklyStats
      },
      {
        path: 'team-stats',
        name: 'TeamStats',
        component: TeamStats
      },
      {
        path: 'projects',
        name: 'Projects',
        component: Projects
      },
      {
        path: 'work',
        name: 'Work',
        component: Work
      }
    ]
  },
  {
    path: '/admin',
    component: Layout,
    meta: { requireAdmin: true },
    children: [
      {
        path: 'permissions',
        name: 'Permissions',
        component: () => import('@/views/admin/Permissions.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const userRole = localStorage.getItem('userRole')
  
  // 检查管理员权限
  if (to.matched.some(record => record.meta.requireAdmin)) {
    if (userRole !== 'admin') {
      next({ path: '/' })
      return
    }
  }
  
  // 检查是否需要登录
  if (to.meta.noRequireAuth || isLoggedIn) {
    next()
  } else {
    next({ path: '/login' })
  }
})

export default router 